<template>
  <van-nav-bar title="罗盘监听" />
  <div>

    <van-cell-group>
    </van-cell-group>
    <van-button v-if="stopLocation" type="primary" style=" margin-top: 20px;"
      @click="startIntervalCompass">开始监听罗盘</van-button>
    <van-button v-else type="primary" style=" margin-top: 20px;" @click="stopIntervalCompass">停止持续罗盘</van-button>
  </div>
  <van-cell-group inset>
    <template v-for="(item,key) in data.locationList" :key="key">
      <div>{{ item.time }}</div>
      <div>{{ item.str }}</div>
    </template>
 
  </van-cell-group>
</template>

<script setup lang='ts' name=''>
import { reactive, ref } from "vue";


// Your script here
const stopLocation = ref(true)
let data = reactive({
  locationList: [] as any[],
});


const startIntervalCompass = () => {
  console.log("startIntervalLocation");
  var interval = 2; //定位周期 5s.
  var data = JSON.stringify({
    interval
  });
  (window as any).whJSBridge.startIntervalCompass(intervalCompassCallback, data).then(
    function (res: any) {
      console.log("启动罗盘监听成功");
      stopLocation.value = false
    }).catch(function (err: any) {

      if ('object' == typeof err) {
        alert('启动罗盘出错：' + JSON.stringify(err))
      } else {
        alert('启动罗盘出错：' + err)
      }
    });
}

//周期性的接收到返回的定位信息
function intervalCompassCallback(resStr: any) {
  const res = JSON.parse(resStr)


  if (res.flag) {
    data.locationList.unshift({
      time: timestampToDateFormat(Date.now()),
      str: JSON.stringify(res.data)
    })
  } else {
    //这一次返回定位失败
    data.locationList.unshift({
      time: timestampToDateFormat(Date.now()),
      str: "获取罗盘失败："+res.msg
    })
  }
}

function stopIntervalCompass() {
  console.log("stopIntervalCompass");
  (window as any).whJSBridge.stopIntervalCompass().then(
    function (res: any) {
      console.log("关闭罗盘监听成功");
      stopLocation.value = true;
    }).catch(function (err: any) {

      if ('object' == typeof err) {
        console.log('关闭罗盘监听出错：' + JSON.stringify(err))
      } else {
        console.log('关闭罗盘监听出错：' + err)
      }
    });
}


function timestampToDateFormat(timestamp:number) {
  const dateObj = new Date(timestamp); // 创建Date对象
  const year = dateObj.getFullYear(); // 获取年份
  const month = ("0" + (dateObj.getMonth() + 1)).slice(-2); // 获取月份，并补零
  const day = ("0" + dateObj.getDate()).slice(-2); // 获取日期，并补零
  
  return `${year}-${month}-${day}`; // 返回转换后的日期格式
}
</script>

<style scoped>
/* Your styles here */
</style>